package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.base.model.PageParams;
import com.xuecheng.base.model.PageResult;
import com.xuecheng.content.mapper.*;
import com.xuecheng.content.model.dto.*;
import com.xuecheng.content.model.po.*;
import com.xuecheng.content.service.CourseBaseInfoService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.security.Key;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Autowired
    CourseBaseMapper courseBaseMapper;
    @Autowired
    CourseCategoryMapper courseCategoryMapper;
    @Autowired
    CourseMarketMapper courseMarketMapper;
    @Autowired
    TeachplanMapper teachplanMapper;
    @Autowired
    CourseTeacherMapper courseTeacherMapper;

    @Override
    public PageResult<CourseBase> selectList(Long companyId,PageParams pageParams, QueryCourseParamsDto queryCourseParamsDto) {
        //设置查询条件
        LambdaQueryWrapper<CourseBase> courseBaseLambdaQueryWrapper = new LambdaQueryWrapper<CourseBase>();
        //课程名称
        courseBaseLambdaQueryWrapper.like(StringUtils.isNotEmpty(queryCourseParamsDto.getCourseName()), CourseBase::getName, queryCourseParamsDto.getCourseName());
        //分布状态
        courseBaseLambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getAuditStatus()), CourseBase::getAuditStatus, queryCourseParamsDto.getAuditStatus());
        //审核状态
        courseBaseLambdaQueryWrapper.eq(StringUtils.isNotEmpty(queryCourseParamsDto.getPublishStatus()), CourseBase::getStatus, queryCourseParamsDto.getPublishStatus());
        //只能查询自己机构的课程
        courseBaseLambdaQueryWrapper.eq(CourseBase::getCompanyId,companyId);
        //分页
        Page<CourseBase> courseBasePage = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        Page<CourseBase> page = courseBaseMapper.selectPage(courseBasePage, courseBaseLambdaQueryWrapper);
        PageResult<CourseBase> result = new PageResult<CourseBase>(page.getRecords(), page.getTotal(), page.getCurrent(), page.getSize());
        return result;
    }

    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBaseInfo(Long companyId, AddCourseDto addCourseDto) {
        //数据校验
        //已采用jrs303校验
        //拷贝课程的数据信息
        CourseBase courseBase = new CourseBase();
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(addCourseDto,courseBase);
        //设置默认审核状态
        courseBase.setAuditStatus("202002");
        //设置默认发布状态
        courseBase.setStatus("203001");
        //设置机构id
        courseBase.setCompanyId(companyId);
        //设置添加时间
        courseBase.setCreateDate(LocalDateTime.now());
        //插入课程信息表
        int insert = courseBaseMapper.insert(courseBase);
        System.out.println(courseBase);
        //获取该课程信息的id与营销信息一一对应
        Long id = courseBase.getId();
        System.out.println(id);
        //拷贝课程的营销信息
        courseMarket.setId(id);
        BeanUtils.copyProperties(addCourseDto,courseMarket);

        //判断是否选择消费方法
        System.err.println(courseMarket);
        String charge = courseMarket.getCharge();
        if (StringUtils.isEmpty(charge)){
            System.err.println(courseMarket);
            throw new RuntimeException("消费方式为空！");
        }
        if (charge.equals("201001")){
            System.err.println(courseMarket);
            Float price = courseMarket.getPrice();
            if ((Objects.isNull(price))||(price.floatValue() <= 0)){
                XueChengPlusException.cast("消费方式为收费但价格不合法！");
            }
        }
        //查询该课程是否存在营销信息
        CourseMarket courseMarket1 = courseMarketMapper.selectById(courseMarket.getId());
        if (courseMarket1==null){
            int i1 = courseMarketMapper.insert(courseMarket);
        }else {
            BeanUtils.copyProperties(courseMarket,courseMarket1);
            courseMarket1.setId(courseMarket.getId());
            //更新
            int i2 = courseMarketMapper.updateById(courseMarket1);
        }
        return queryCourseInfo(courseBase.getId());
    }
    //返回的信息整合方法（分别插入数据后再一并返回）
    @Override
    public CourseBaseInfoDto queryCourseInfo(Long id){
        CourseBase courseBase = courseBaseMapper.selectById(id);
        CourseMarket courseMarket = courseMarketMapper.selectById(id);
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        BeanUtils.copyProperties(courseMarket,courseBaseInfoDto);
        //根据分类id填充分类的名称
        CourseCategory courseCategory1 = courseCategoryMapper.selectById(courseBaseInfoDto.getSt());
        courseBaseInfoDto.setStName(courseCategory1.getName());
        CourseCategory courseCategory2 = courseCategoryMapper.selectById(courseBaseInfoDto.getMt());
        courseBaseInfoDto.setMtName(courseCategory2.getName());
        return courseBaseInfoDto;
    }

    @Override
    public CourseBaseInfoDto updateCourseInfo(Long companyId,EditCourseDto editCourseDto) {
        //根据id获取机构id，以此判断是否违规
        CourseBase courseBase = courseBaseMapper.selectById(editCourseDto.getId());
        BeanUtils.copyProperties(editCourseDto,courseBase);
        CourseMarket courseMarket = courseMarketMapper.selectById(editCourseDto.getId());
        BeanUtils.copyProperties(editCourseDto,courseMarket);
        if (!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("6，只能修改自己机构的课程");
        }
        int i1 = courseBaseMapper.updateById(courseBase);
        int i2 = courseMarketMapper.updateById(courseMarket);
        if (i1<1||i2<1){
            XueChengPlusException.cast("更新失败啰66");
        }
        return queryCourseInfo(editCourseDto.getId());
    }

    @Override
    public void deleteCourseInfo(Long companyId,Long id) {
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (!companyId.equals(courseBase.getCompanyId())){
            XueChengPlusException.cast("只能删除本机构的课程");
        }
        //删除基本信息
        courseBaseMapper.deleteById(id);
        //删除营销信息
        courseMarketMapper.deleteById(id);
        //删除课程计划
        LambdaQueryWrapper<Teachplan> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Teachplan::getCourseId,id);
        teachplanMapper.delete(lambdaQueryWrapper);
        //删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.eq(CourseTeacher::getCourseId,id);
        courseTeacherMapper.delete(lambdaQueryWrapper1);
    }
}
